﻿using System;
using System.Collections.Generic;

namespace Basic
{
    /// <summary>
    /// 版本号
    /// </summary>
    public class Version
    {
        /// <summary>
        /// 主版本号
        /// </summary>
        public readonly int Main;

        /// <summary>
        /// 次版本号
        /// </summary>
        public readonly int Middle;

        /// <summary>
        /// 热更版本号
        /// </summary>
        public readonly int Low;

        /// <summary>
        /// 版本序号
        /// </summary>
        public readonly int Serial;

        public string Marshal()
        {
            return string.Format("{0}.{1}.{2}.{3}", Main, Middle, Low, Serial);
        }

        /// <summary>
        /// 比较两个版本号的关系
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns>-1 left比right低; 0 left与right一致; 1 left比right高</returns>
        public static int Compare(Version left, Version right)
        {
            if (left.Serial < right.Serial)
            {
                return -1;
            }
            else if (left.Serial == right.Serial)
            {
                return 0;
            }
            return 1;
        }

        private Version(int Main, int Middle, int Low, int Serial)
        {
            this.Main = Main;
            this.Middle = Middle;
            this.Low = Low;
            this.Serial = Serial;
        }

        /// <summary>
        /// 从字符串解析版本号
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public static Version ParseFromString(string version)
        {
            version = version.Trim();
            var datas = version.Split('.');
            if (datas.Length != 4)
            {
                return null;
            }

            for (int i = 0; i < datas.Length; ++i)
            {
                datas[i] = datas[i].Trim();
                foreach (var ch in datas[i])
                {
                    if (!Char.IsNumber(ch))
                    {
                        return null;
                    }
                }
            }

            return new Version(int.Parse(datas[0]), int.Parse(datas[1]), int.Parse(datas[2]), int.Parse(datas[3]));
        }
    }
}
